from flask import Flask, request, jsonify
from flask_httpauth import HTTPBasicAuth
from flask_cors import CORS
from datetime import datetime, timedelta
import csv
import secrets
import redis
import psutil
import os
import ssl
import json
import time

app = Flask(__name__)
auth = HTTPBasicAuth()
CORS(app)
r = redis.Redis()

# 载入用户名和密码到字典中（从/etc/ansible/users.csv文件）
users = {}
with open('/etc/ansible/users.csv', 'r') as csvfile:
    csv_reader = csv.reader(csvfile)  # 使用csv.reader读取csvfile中的文件
    header = next(csv_reader)  # 读取第一行每一列的标题
    for row in csv_reader:  # 将csv 文件中的数据保存到data中
        for index in row:
            info = index.split(";")
            users[info[1]] = info[2]


# 配置SSL证书和密钥
# context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
# context.load_cert_chain(certfile='/path/to/cert.pem', keyfile='/path/to/key.pem')
@app.route("/")
def home():
    return "Welcome to the Infrastructure API!"


# 认证函数
@auth.verify_password
def verify_password(username, password):
    if username in users and password == users[username]:
        return username


# 路由: 获取系统统计数据
@app.route('/stats', methods=['GET'])
@auth.login_required
def get_stats():
    ram_free = psutil.virtual_memory().available // 1024 // 1024
    uptime = str(datetime.now() - datetime.fromtimestamp(psutil.boot_time()))
    api_pid = os.getpid()
    api_prio = os.nice(0)
    total_proc = psutil.cpu_count()
    return jsonify({
        'ram_free': ram_free,
        'uptime': uptime,
        'api_pid': api_pid,
        'api_prio': api_prio,
        'total_proc': total_proc
    })


# 路由: 登录并获取访问令牌
@app.route('/login', methods=['POST'])
@auth.login_required
def login():
    token = secrets.token_hex(16)
    r.set(token, auth.current_user())
    r.expire(token, timedelta(seconds=90))
    return jsonify({'token': token})


# 路由:注销用户
@app.route('/logout', methods=['POST'])
@auth.login_required
def logout():
    token = request.headers.get('token')
    r.delete(token)
    return jsonify({'message': 'Logged out'})


# 路由: 获取当前用户
@app.route('/whoami', methods=['GET'])
@auth.login_required
def whoami():
    return jsonify({'username': auth.current_user()})


@app.route("/customers/", methods=["PUT"])
@auth.login_required
def deploy_customer():
    customer_data = request.get_json()

    # Extract the required parameters from the customer_data dictionary
    name = customer_data.get("name")
    domain_prefix = customer_data.get("domain_prefix")
    username = customer_data.get("username")
    password = customer_data.get("password")
    message = customer_data.get("message")

    # Read the existing customers.json file
    with open("/etc/ansible/customers.json", "r") as file:
        customers = json.load(file)

    # Check if name, domain_prefix, and username are unique
    for customer in customers:
        if customer["name"] == name or customer["domain_prefix"] == domain_prefix or customer["username"] == username:
            return "Duplicate values found", 403  # Return 403 Forbidden error

    # Create a new customer dictionary
    new_customer = {
        "name": name,
        "domain_prefix": domain_prefix,
        "username": username,
        "password": password,
        "message": message
    }

    # Append the new customer to the existing customers list
    customers.append(new_customer)

    # Update the customers.json file with the new data
    with open("/etc/ansible/customers.json", "w") as file:
        json.dump(customers, file)

    # Run the 6-customers.yml playbook using Ansible command
    # subprocess.run(["ansible-playbook", "-i", "inventory.ini", "6-customers.yml"], capture_output=True)

    return "Customer deployed successfully", 200


# 全局变量用于记录成功和失败请求的次数
# 全局计数器变量
request_counts = []


# 记录 API 请求状态
@app.before_request
def record_request():
    global request_counts
    request_counts.append((time.time(), True))  # 成功请求
    request_counts = [(ts, success) for ts, success in request_counts if ts >= time.time() - 3600]  # 仅保留最近 1 小时内的记录


# 获取过去指定时间段内的请求状态
def get_request_status(duration):
    global request_counts
    end_time = time.time()
    start_time = end_time - duration
    successful_requests = sum(1 for ts, success in request_counts if start_time <= ts <= end_time and success)
    failed_requests = sum(1 for ts, success in request_counts if start_time <= ts <= end_time and not success)
    return successful_requests, failed_requests


# 获取过去 5 分钟内的请求状态
def get_request_status_5mins():
    return get_request_status(300)


# 获取过去 1 小时内的请求状态
def get_request_status_1h():
    return get_request_status(3600)


# 读取请求状态并返回数据
@app.route('/healthz', methods=['GET'])
def get_health_status():
    successful_requests_5mins, failed_requests_5mins = get_request_status_5mins()
    successful_requests_1h, failed_requests_1h = get_request_status_1h()
    response = {
        'failed_requests_1h': failed_requests_1h,
        'failed_requests_5mins': failed_requests_5mins,
        'successful_requests_1h': successful_requests_1h,
        'successful_requests_5mins': successful_requests_5mins
    }
    return jsonify(response)


if __name__ == '__main__':
    # app.run(host='10.22.0.50', port=443, ssl_context=context, threaded=True)
    app.run(host='0.0.0.0', port=443, threaded=True)

